package com.cgg.stock.deal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cgg.stock.common.exception.TradeOrderNotNullException;
import com.cgg.stock.common.pojo.HoldStock;
import com.cgg.stock.common.pojo.TradeOrder;
import com.cgg.stock.deal.mapper.DealMapper;
import com.cgg.stock.deal.service.IDealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: 处理订单业务层实现类
 * @Date: 2023/2/16 16:02
 * @Author: SinkDream
 */
@Service
public class DealServiceImpl implements IDealService {
    @Autowired
    private DealMapper dealMapper;

    @Override
    public void dealOrder(List<TradeOrder> tradeOrders) throws Exception {
        if (CollectionUtils.isEmpty(tradeOrders)){
            throw new TradeOrderNotNullException();
        }
        for (TradeOrder tradeOrder : tradeOrders) {
            Long buyUserId = tradeOrder.getBuyUserId();
            Long sellUserId = tradeOrder.getSellUserId();
            String stockId = tradeOrder.getStockId();
            BigDecimal price = tradeOrder.getPrice();
            Integer num = tradeOrder.getNum();
            //处理买方持仓股
            HoldStock holdStock = dealMapper.selectByAccountAndStockId(buyUserId,stockId);
            if (holdStock == null){
                holdStock = new HoldStock();
                holdStock.setStockId(stockId);
                holdStock.setUserAccount(buyUserId);
                holdStock.setTradePrice(price);
                holdStock.setTotalNum(num);
                holdStock.setAvailableNum(0);
                holdStock.setTradeTime(new Date());
                holdStock.setStatus(1);
                dealMapper.insert(holdStock);
            }else {
                holdStock.setTotalNum(holdStock.getTotalNum()+num);
                dealMapper.updateTotalByAccountAndStockId(holdStock.getTotalNum(),buyUserId,stockId);
            }
            //处理卖方持仓股
            HoldStock holdStock2 = dealMapper.selectByAccountAndStockId(sellUserId,stockId);
            Integer sellTotalNum = holdStock2.getTotalNum();
            sellTotalNum -= num;
            if (sellTotalNum == 0){
                dealMapper.updateStatusByAccountAndStockId(sellUserId,stockId);
            }
            holdStock2.setTotalNum(sellTotalNum);
            dealMapper.updateTotalByAccountAndStockId(holdStock.getTotalNum(),sellUserId,stockId);
        }
    }
}
